<template>
    <div>
        <el-drawer title="选择撰稿" v-model="isSelectDeparment" direction="rtl" size="80%">
            <seleceDepartment :person="Qdata.writer.id" @setCanSee="setCanSee"></seleceDepartment>
            撰稿仅可设置1人，可置空
        </el-drawer>

        <div ref="QBody" :column="1" :colon=false style="background-color: white;">
            <div>撰稿：{{ writer.name }}</div>
            <div>审核：<span v-html="shenType(Qdata.shen)"></span></div>
        </div>
        <el-button type="primary" size="small" @click="setWriter">编辑授权</el-button>
        <el-button type="primary" size="small"
            @click="() => { router.push(`/write?id=${props.id}&type=q`) }">编辑文字</el-button>
        <el-button type="primary" size="small" @click="shotPic()">生成图片</el-button>
        <el-descriptions :title="Qdata.imgurls ? '配图' : '无配图'" :column="1"></el-descriptions>

        <el-card v-if="Qdata.imgurls">
            <span v-for="o, k in Qdata.imgurls.split(',')" style="position: relative;">
                <img :src="o" style="width:50%" :key="k">
                <el-tag type="danger" style="position: absolute;left:0" v-show="isImgEdit" @click="delImg(k)">
                    删除
                </el-tag>
            </span>
        </el-card>

        <input type="file" name="" @change="uploadImg" ref="upimg" style="position: absolute;top:-9999px">
        <el-button type="primary" size="small" v-show="isImgEdit" @click="upimg && upimg.click()">上传<i
                class="el-icon-upload el-icon--right"></i>
        </el-button>
        <br>
        <el-button type="primary" icon="el-icon-edit" size="small" @click="setImg">{{ isImgEdit ? "保存" : "编辑配图"
        }}</el-button>
        <br><br>
        <!-- <el-button type="primary" icon="el-icon-refresh" circle></el-button> -->


        <el-dialog title="生成图片" :visible.sync="toimgDialog" width="30%">
            <img :src="toimgUrl" width="100%">
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="toimgDialog = false">关闭</el-button>
            </span>
        </el-dialog>

    </div>
</template>

   
<script setup lang="ts">
import messageApi from "@/api/message"
// import seleceDepartment from "../selectDeparment.vue"
// import Dom2pic from "dom2pic"
import domtoimage from '@/dom2img/dom2img'
import face from "@/api/face.js"
import { giteeUpload } from "@/api/FileGitee"
import seleceDepartment from "../selectDepartment.vue"
import bus from "@/libs/bus.ts"


import { ref, Ref, nextTick } from "vue"
import { useRouter } from "vue-router"
import { ElButton, ElDescriptions, ElCard, ElDialog, ElMessage, ElDrawer } from "element-plus"
import QType from "@/types/Q"
let props = defineProps(['id'])
let router = useRouter()

let Qdata: Ref<QType> = ref({} as QType)
let QBody: Ref<HTMLElement | undefined> = ref()
let upimg: Ref<HTMLInputElement | undefined> = ref()
let writer: any = ref({})

let isSelectDeparment: Ref<boolean> = ref(false)
let isImgEdit: Ref<boolean> = ref(false)
let toimgDialog: Ref<boolean> = ref(false)
let toimgUrl: Ref<string> = ref("")

async function refresh() {
    checkBrowser()
    let qInfo = await messageApi.getQ(props.id)
    // if (qInfo.data.length == 0) {
    //     this.$emit("hasQ", 0)
    //     return
    // }
    // this.$emit("hasQ", id)
    Qdata.value = qInfo.data
    let regex2 = /\{(.+?)\]/g;
    let str = Qdata.value.message
    for (let emo of str.match(regex2) || []) {
        str = str.replace(emo, String.fromCodePoint(~~emo.replace(/\{/, "").replace(/\]/, "")));
    }
    Qdata.value.message = str
    writer.value = qInfo.data.writer
}
refresh()

function setWriter() {
    isSelectDeparment.value = true
}
function shotPic() {
    nextTick(() => {
        if (!QBody.value) return
        let images = QBody.value.getElementsByTagName('img');
        for (let img of images) {
            img.src = face.getLocationFace(img.src.replace(/[^-](\d)-|[^\d]/ig, ''))
        }

        let tempNode = document.createElement("div")
        let imgHead = document.createElement("div")
        imgHead.innerHTML = `
            <div><div>软件传媒信息平台</div><div>2023</div></div>
            <img height="40" width="40" src="">
            `
        imgHead.style.cssText = "display:flex;justify-content:space-between;align-items: center;"
        tempNode.style.cssText = "width:450px;padding:20px;box-sizing:border-box;background:white;"
        tempNode.appendChild(imgHead)
        tempNode.appendChild(QBody.value.cloneNode(true))
        document.body.appendChild(tempNode)
        const node = tempNode 
        console.log(tempNode)
        const option = {
            width:tempNode.offsetWidth, // 高度宽度自行设定
            height: tempNode.offsetHeight,
            scale: 4 // 后面的字表示需要把一个像素转为几个像素
        }
        domtoimage
            .toPng(node, { ...option })
            .then((dataUrl: string) => {
                //输出图片的Base64,dataUrl
                // 下载到PC
                toimgDialog.value = true
                toimgUrl.value = dataUrl
                const a = document.createElement('a') // 生成一个a元素
                const event = new MouseEvent('click') // 创建一个单击事件
                a.download = "官Q截图-" + props.id// 设置图片名称没有设置则为默认
                a.href = dataUrl // 将生成的URL设置为a.href属性
                a.dispatchEvent(event) // 触发a的单击事件
                document.body.removeChild(tempNode)
            })
            .catch(function (error: Error) {
                console.error('oops, something went wrong!', error)
                document.body.removeChild(tempNode)
            })
    })
}
function setImg() {
    if (isImgEdit.value) {
        messageApi.setQImg(props.id, Qdata.value.imgurls).then((res) => {
            if (res.code == 1) {
                ElMessage.success('保存成功');
            }
        })
    }
    isImgEdit.value = !isImgEdit.value
}
function shenType(type: 0 | 1 | 2 | 3 | 4 | 5) {
    switch (type) {
        case 0: return "未知";
        case 1: return "一审中";
        case 2: return "二审中";
        case 3: return "<b style='color:green'>已通过</b>";
        case 4: return "<b style='color:green'>已发稿</b>";
        case 5: return "<b style='color:red'>驳回</b>";
    }
}
function setCanSee(result) {
    if (result.length > 1) {

    } else if (result.length == 0) {
        messageApi.setWrite(props.id, "0").then((res) => {
            if (res.code == 1) {

            }
        })
    } else {
        messageApi.setWrite(props.id, result[0].id).then((res) => {
            if (res.code == 1) {
                bus.emit("changeState", ["middle", `编辑成功`]);
            }
        })
    };
    // this.refresh()
}
function delImg(k: number) {
    let imgs = Qdata.value.imgurls.split(",")
    imgs.splice(k, 1)
    Qdata.value.imgurls = imgs.join(",")
}
function uploadImg() {
    let file = upimg.value?.files;
    if (file) {
        if (!/image\/\w+/.test(file && file[0].type)) {
            bus.emit("changeState", ["middle", `只能选择图片`]);
            return false;
        }
        if (file[0].size > 1e9) {
            alert("这么大？太可怕了吧？？");
            return false;
        }
        if (file[0].size > 2e6) {
            alert("图片不得超过2MB");
            return false;
        }
        new Promise((resolve) => {
            bus.emit("changeState", ["middle", `上传中`]);
            let reader = new FileReader();
            reader.readAsArrayBuffer(file![0]);
            reader.onload = function () {
                reader.result && resolve(arrayBufferToBase64(reader.result as ArrayBuffer));
            }
        }).then(async (res: unknown): Promise<void> => {
            if (typeof res !== 'string') return
            let uploadRe = await giteeUpload(file![0].name, res, props.id, 'Q')
            let imgs = Qdata.value.imgurls.split(",")
            imgs.push(uploadRe.data.msg.content.download_url)
            Qdata.value.imgurls = imgs.join(",")
            bus.emit("changeState", ["middle", `上传成功`]);
        })

    }
}

function checkBrowser() {
    if (typeof (FileReader) === 'undefined') {
        alert("抱歉，当前浏览器不支持 FileReader，你可能无法图片上传。请使用现代浏览器操作");
    }
}
function arrayBufferToBase64(buffer: ArrayBuffer) {
    let binary = '';
    let bytes = new Uint8Array(buffer);
    let len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
}
</script>

<style>
video {
    max-width: 300px;
}
</style>
